<template>
  <div class="container" v-loading="loading" element-loading-text="努力加载中...">
    <div class="content">
      <div class="title">
        <div class="title-text">体位、体动</div>
      </div>
      <div class="section-title">
        <el-text class="section-title-text">不同体位占睡眠效率的比例:</el-text>
      </div>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div id="bodyPerChart" class="chart"></div>
        </div>
      </div>
      <div class="section-title">
        <el-text class="section-title-text">体位分时图:</el-text>
      </div>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div id="bodyPosChart" class="chart"></div>
        </div>
      </div>
      <div class="section-title">
        <el-text class="section-title-text">体动分时图:</el-text>
      </div>
      <div class="chart-container">
        <div class="chart-wrapper">
          <div id="bodyMovChart" class="chart"></div>
        </div>
      </div>
      <div class="evaluation-container">
        <div class="evaluation-content">
          <div class="evaluation-header">
            <div class="icon">
              <font-awesome-icon :icon="['fas','fa-file-alt']" size="2x" class="icon-color"></font-awesome-icon>
            </div>
            <div class="evaluation-title">
              <el-text class="evaluation-title-text">体位、体动评估结果：</el-text>
            </div>
            <el-button v-if="enableEdit" class="edit-button" @click="showEditInput">
              <font-awesome-icon :icon="['fas','fa-pencil-alt']" class="edit-icon"></font-awesome-icon>
              <el-text class="edit-text">编辑</el-text>
            </el-button>
          </div>
          <div class="evaluation-body">
            <el-input type="textarea" class="evaluation-input" v-model="currentUserBodyData.evaluation" v-if="editMode"></el-input>
            <el-text v-else :span="24" class="evaluation-display">
              {{ currentUserBodyData.evaluation }}
            </el-text>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import '@/assets/css/reportCard.css';
import {ref, onMounted, onUnmounted, reactive, watch, markRaw, nextTick} from "vue";
import * as echarts from "echarts";
import sleepData from "@/api/sleepData.js";
onMounted(() => {
  getBodyData(props.currentReportId);
  // 监听窗口大小变化
  window.addEventListener('resize', resizeCharts);
});
onUnmounted(() => {
  if (currentUserBodyData.value.evaluation === evaluationBackup.value){

  }else {
    const updateBodyDataDto = {
      reportId: props.currentReportId,
      evaluation: currentUserBodyData.value.evaluation
    }
    sleepData.updatePositionEvaluate(updateBodyDataDto).then((res)=>{
      if (res.data.code === 200){

      }
    }).catch((err)=>{
      console.log(err)
    })
  }
  disposeChart()
});
const props = defineProps({
  currentReportId: Number,
  enableEdit:Boolean
});
watch(() => props.currentReportId, (newId) => {
  getBodyData(newId);
});
watch(() => props.enableEdit, (newValue) => {
  enableEdit.value = newValue
});
const enableEdit = ref(props.enableEdit)
const loading = ref(false)
const evaluationBackup = ref('')
const getBodyData = (reportId)=>{
  loading.value = false
  sleepData.getPositionData(reportId).then((res)=>{
    const proportionList = res.data.data.proportionList;
    // 将数据分别提取到两个数组中
    const names = proportionList.map(item => item.name);
    const positionTime = res.data.data.positionTime;
    // 处理数据
    const timeArray = positionTime.times;
    const positionArray = positionTime.position;
    // 将时间和位置组合成对象
    const combinedPositionData = timeArray.map((timestamp, index) => ({
      time: timestamp,
      position: positionArray[index]
    }));
    // 按照时间进行排序
    combinedPositionData.sort((a, b) => a.time - b.time);
    const moveExtent = res.data.data.moveExtent;
    // 计算打鼾事件的具体时间点
    const startTime = moveExtent.startTime;
    const frequency = moveExtent.frequency;
    const extents = moveExtent.extents;
    const moveTimePoints = extents.map((label, index) => {
      const timestamp = startTime + index * frequency;
      const date = new Date(timestamp);
      // 格式化时间为 HH:mm 格式
      return ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
    });
    nextTick(() => {
      createBodyPerChart(names, proportionList);
      createBodyPosChart(combinedPositionData);
      createBodyMovChart(moveTimePoints, extents);
    });
    currentUserBodyData.value = res.data.data
    evaluationBackup.value = currentUserBodyData.value.evaluation
  }).catch((err)=>{
    console.log(err)
  }).finally(() => {
    loading.value = false; // 使用箭头函数包装
  });
}

//图表创建
const bodyPerChartInstance = ref(null);
const bodyPosChartInstance = ref(null);
const bodyMovChartInstance = ref(null);
const createBodyPerChart = (names, proportionList) => {
  bodyPerChartInstance.value = markRaw(echarts.init(document.getElementById("bodyPerChart")));
  bodyPerChartInstance.value.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical', // 设置图例垂直排列
      right: 10, // 设置图例距离右侧的距离
      top: 'center', // 设置图例在垂直方向上居中对齐
      itemGap: 10, // 设置图例项之间的间距
      itemWidth: 30, // 设置图例项的宽度
      itemHeight: 15, // 设置图例项的高度
      textStyle: {
        fontSize: 12, // 设置图例项的字体大小
      },
      formatter: function(name) { // 自定义图例项的显示格式
        const maxLength = 3; // 每行最多显示的图例个数
        if (name.length > maxLength) {
          return name.slice(0, maxLength) + '\n' + name.slice(maxLength);
        }
        return name;
      },
      data: names
    },
    series: [
      {
        name: '占比',
        type: 'pie',
        radius: '80%',
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '30',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: proportionList
      }
    ]
  }, true);
}
const createBodyPosChart = (combinedPositionData)=>{
  // 基于准备好的dom，初始化echarts实例
  bodyPosChartInstance.value = markRaw(echarts.init(
      document.getElementById("bodyPosChart")));
  bodyPosChartInstance.value.setOption({
    grid: {
      left: '5%',
      right: '5%',
      top: '5%', // 调整top值
      bottom: '0%', // 调整bottom值
      containLabel: true,
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        animation: false
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: true, // 设置boundaryGap为true
      data: combinedPositionData.map(data => formatTime(data.time)), // 使用排序后的时间数组
    },
    yAxis: {
      type: 'category',
      data: ['左侧', '仰卧', '右侧','俯卧' ,'直立'],
    },
    series: [
      {
        name: '体位',
        type: 'line',
        step: 'middle',
        symbol: 'none', // 隐藏圆点
        data: combinedPositionData.map(data => [formatTime(data.time), data.position]), // 使用排序后的组合数据

      },
    ],
  },true);
}
const createBodyMovChart = (moveTimePoints,extents)=>{
  bodyMovChartInstance.value = markRaw(echarts.init(
      document.getElementById("bodyMovChart")));
  bodyMovChartInstance.value.setOption({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      top: '10%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: moveTimePoints,
      splitLine: {
        show: false
      }
    },

    yAxis: {
      type: 'value',
      splitLine: {
        show: false
      },
      axisLabel:false
    },


    series: [{
      type: 'line',
      smooth: true,
      data: extents,
      symbol: 'none', // 隐藏圆点
    }]
  });
}

//图表自适应
const resizeCharts = () => {
  if (bodyPerChartInstance.value) {
    bodyPerChartInstance.value.resize();
  }
  if (bodyPosChartInstance.value) {
    bodyPosChartInstance.value.resize();
  }
  if (bodyMovChartInstance.value) {
    bodyMovChartInstance.value.resize();
  }
};
const disposeChart = ()=>{
  // 销毁图表实例
  if (bodyPerChartInstance.value) {
    bodyPerChartInstance.value.dispose();
  }
  if (bodyPosChartInstance.value) {
    bodyPosChartInstance.value.dispose();
  }
  if (bodyMovChartInstance.value) {
    bodyMovChartInstance.value.dispose();
  }
  // 移除事件监听器
  window.removeEventListener('resize', resizeCharts);
}
//编辑
const editMode = ref(false)
const showEditInput = () => {
  editMode.value = !editMode.value;
};
const currentUserBodyData = ref({
  evaluation:''
})
// 将时间戳格式化为可读的时间字符串
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  // 获取小时和分钟
  const hours = date.getHours().toString().padStart(2, '0'); // 补0操作，确保两位数
  const minutes = date.getMinutes().toString().padStart(2, '0');
  // 返回格式化后的时间字符串
  return hours + ':' + minutes;
};
</script>
<<style scoped>
.container {
  width: 90%;
  height: 100%;
  background-color: #EFF2F9;
  border-radius: 20px;
}
.content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title {
  width: 100%;
  height: 5%;
  margin-top: 2%;
}
.title-text {
  font-size: 18px;
  height: 100%;
  margin-left: 20px;
  align-items: center;
  display: flex;
}
.section-title {
  width: 100%;
  height: 3%;
  margin-top: 5px;
  margin-bottom: 5px;
}
.section-title-text {
  font-size: 16px;
  margin-left: 5%;
}
.chart-container {
  width: 100%;
  height: 25%;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chart-wrapper {
  width: 90%;
  height: 100%;
  border-radius: 10px;
  background-color: white;
}
.chart {
  width: 100%;
  height: 100%;
}
.evaluation-container {
  width: 100%;
  height: 15%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}
.evaluation-content {
  width: 95%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.evaluation-header {
  width: 100%;
  height: 30%;
  display: flex;
}
.icon {
  height: 100%;
}
.icon-color {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
}
.evaluation-title {
  height: 100%;
  display: flex;
}
.evaluation-title-text {
  font-size: 17px;
  font-weight: 510;
}
.edit-button {
  height: 100%;
  margin-left: auto;
  background-color: #EFF2F9;
  border: none;
}
.edit-icon {
  color: #3DD986;
  margin-left: 10px;
  margin-right: 10px;
  width: 20px;
  height: 20px;
}
.edit-text {
  font-size: 17px;
  color: #3DD986;
}
.evaluation-body {
  width: 100%;
  height: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.evaluation-input {
  height: 100%;
  width: 95%;
}
.evaluation-display {
  width: 90%;
  font-size: 15px;
  margin-left: 30px;
  margin-top: 10px;
}
</style>
